package inet.app.controller.connect;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

public class JsonParser {
	public static boolean isConnecting = false;
	private InputStream is = null;
	static JSONObject jObj = null;
	static String json = "";
	String result;
	// constructor
	public JsonParser() {
		
	}
	public JSONObject getJSONFromUrl(String url) {
		isConnecting = true;
		// Making HTTP request
		
		try {
			// defaultHttpClient
			DefaultHttpClient httpClient = new DefaultHttpClient();
			System.out.println("Request :" + url);
			HttpGet httpPost = new HttpGet(url);
			HttpResponse httpResponse = httpClient.execute(httpPost);
			HttpEntity httpEntity = httpResponse.getEntity();
			is = httpEntity.getContent();
			BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();
			json = sb.toString();
			System.out.println("--------"+json);
			jObj = new JSONObject(json);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		isConnecting = false;
		return jObj;
	}
	public String getURL(String url) {
		isConnecting = true;
		try {
			DefaultHttpClient httpClient = new DefaultHttpClient();
			System.out.println("Request :" + url);
			HttpGet httpPost = new HttpGet(url);
			HttpResponse httpResponse = httpClient.execute(httpPost);
			HttpEntity httpEntity = httpResponse.getEntity();
			is = httpEntity.getContent();
			BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();
			json = sb.toString();
		} catch (Exception e) {
//			Log.e(e.toString());
			e.printStackTrace();
			return null;
		}
		isConnecting = false;
		return json;
	}
	
}
